<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\BaseController;
use App\Lib\SnsapiLogin;
use App\Models\HoneyBalance;
use App\Models\User;
use App\Services\HoneyBalanceService;
use Dingo\Api\Http\Request;

class AuthController extends BaseController
{
    public function login(Request $request)
    {
        $input = $request->input();

        if (env('API_DEBUG') && !empty($input['user_id'])) {
            $user = User::find($input['user_id']);
            if (!$token = \Auth::guard('api')->fromUser($user)) {
                return $this->failed('登录失败', 401);
            }
            return $this->respondWithToken($token);
        }

        \Log::info("weixin-login-param : " . var_export($input, true));
        $this->validate($request, [
            'code' => 'required',
            'encryptedData' => 'required',
            'iv' => 'required',
        ]);
        $app = $this->miniProgram();

        $session = $app->auth->session($request->code);
        \Log::info("weixin-session : " . var_export($session, true));
        if (isset($session['errcode']) &&  $session['errcode'] > 0)
            return $this->failed($session['errmsg']);

        try {
            $userInfo = $app->encryptor->decryptData(
                $session['session_key'],
                $request->iv,
                $request->encryptedData
            );
            \Log::info("weixin-decrypt : " . var_export($userInfo, true));
        } catch (\Exception $e) {
            \Log::error($e->getMessage());
            return $this->failed('网络异常，请重新操作');
        }

        $user = User::where('union_id', $userInfo['unionId'])->first();
        if (!$user) {
            $user = new User();
            $user->openid = $userInfo['openId'];
            $user->session_key = $session['session_key'];
            $user->nickname = $userInfo['nickName'];
            $user->gender = $userInfo['gender'];
            $user->avatar_url = $userInfo['avatarUrl'];
            $user->union_id = $userInfo['unionId'];
            $user->save();
            HoneyBalanceService::store($user->id,  HoneyBalance::POINT_REG, HoneyBalance::TYPE_REG,0, true);
        } else {
            $user->session_key = $session['session_key'];
            $user->save();
        }

//        $user = User::find("abc");
        if (!$token = \Auth::guard('api')->fromUser($user)) {
            return $this->failed('登录失败', 401);
        }

        return $this->respondWithToken($token);
    }


    public function pc_login_url() {
        $url = \request('return_url');
        $url = SnsapiLogin::getLoginUrl($url);
        return $this->success([
            'url' => $url
        ]);
    }

    public function pc_login(Request $request) {
        $this->validate($request, [
            'code' => 'required'
        ]);
        $code = \request('code');

        try {
            $userInfo = SnsapiLogin::getUserInfo($code);
            \Log::info(var_export($userInfo, true));
            $user = User::where('union_id', $userInfo['unionid'])->first();
            if (!$user) {
                $user = new User();
                $user->openid = $userInfo['openid'];
                $user->nickname = $userInfo['nickname'];
                $user->gender = $userInfo['sex'];
                $user->avatar_url = $userInfo['headimgurl'];
                $user->union_id = $userInfo['unionid'];
                $user->first_login_at = 2;
                $user->save();
                HoneyBalanceService::store($user->id,  HoneyBalance::POINT_REG, HoneyBalance::TYPE_REG,0, true);
            }

            if (!$token = \Auth::guard('api')->fromUser($user)) {
                return $this->failed('登录失败', 401);
            }
            return $this->respondWithToken($token);
        } catch (\Exception $e) {
            return $this->failed($e->getMessage());
        }

    }




}